package com.atguigu.controller;

import com.atguigu.entities.CommonResult;
import com.atguigu.entities.Payment;
import com.atguigu.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Null;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Value("${server.port}")
    private String serverport;

    @Resource
    private DiscoveryClient discoveryClient;

    @Autowired
    private PaymentService paymentService;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("___________插入结果：" + result);
        if(result > 0){
            return new CommonResult(200,"插入成功,port:"+serverport,result);
        }else{
            return new CommonResult(444,"插入失败");
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("___________查询结果：" + payment);
        if(payment != null){
            return new CommonResult(200,"查询成功,port:"+serverport,payment);
        }else{
            return new CommonResult(444,"没有对应记录！查询ID："+id);
        }
    }

    @GetMapping("/payment/getDiscovery")
    public Object getDiscoveryClient(){
        List<String> services = discoveryClient.getServices();//获得所有的服务名
        services.forEach(ser -> {
            System.out.println(ser);
        });
        //通过服务名来获取服务信息
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(ins -> {
            System.out.println("host:" + ins.getHost()+",URL:"+ins.getUri());
        });
        return services.toString()+instances.toString();
    }

    @GetMapping("/payment/timeout")
    public String timeout(){
        try {
//            模拟超时业务，超时三秒钟
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverport;
    }
}
